package team;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

/**
 * This class includes Graphic Design for first selection
 * (Choose from Auto Maker) of initial screen. The auto
 * selection window include three Jlist and 1 JTextArea 
 * to show all available auto maker, model, year and 
 * description.
 * @author Yongxiang, Sean Peng
 *
 */

public class AutoMakerFrame extends JFrame {
	
	private AutoMakerFrame frame = this;
	private String maker;
	private String model;
	private String year;
	private JList<String> makerList;
	private JList<String> modelList;
	private JList<String> yearList;
	private JList<String> descList;
	private DefaultListModel<String> makerListModel;
	private DefaultListModel<String> modelListModel;
	private DefaultListModel<String> yearListModel;
	private DefaultListModel<String> descListModel;
	private JTextArea description;
	private ArrayList<Integer> rLinkList;
	private int rLinkIndex;
	private String[] editInfo;
	private JButton partsButton;
	private JButton addButton;
	private JButton changePartButton;
	private JButton editButton;
	private JButton backButton; 
	private JButton deleteButton;
	private JPanel autoDes;
	private JPanel buttonPanel;
	
	public AutoMakerFrame(final JFrame initialFrame, final boolean authorized){
		
		/*set Title and Size*/
		this.setTitle("Auto Selection");
		this.setSize(800,600);
		this.setVisible(true);
	
		/* Create TextArea for description */
		autoDes = new JPanel();
		buttonPanel = new JPanel();
		
		//To store edit information
		editInfo = new String[8];
		
		/*Create maker list and Set up maker list's property*/
//		String[] makers = Result.getAutoMaker();
		String[] makers = AutoMaker.getMakerName();
		makerListModel = new DefaultListModel<String>();
		for(String maker : makers)
			makerListModel.addElement(maker);
			
		makerList = new JList<String>(makerListModel);
		makerList.setVisibleRowCount(5);
		makerList.setBorder(BorderFactory.createTitledBorder("Maker:"));
		makerList.addListSelectionListener(new ListSelectionListener(){

			@Override
			public void valueChanged(ListSelectionEvent e) {
				
				//Delete all information  if new maker is cliced
				for(int i=1; i<editInfo.length; i++){
					editInfo[i] = null;
				}
				model = null;
				year = null;
				
				//getValueIsAdjusting becomes false
				if(!e.getValueIsAdjusting()){
						
					JList<String> list = (JList<String>)e.getSource();
					maker = (String) list.getSelectedValue();
					editInfo[0] = maker;
					modelListModel.clear();
					yearListModel.clear();
					descListModel.clear();
					maker = AutoMaker.makerTable.get(maker);
					String[] models = Result.getModel(maker);
					for( String model : models)
							modelListModel.addElement(model);
					}
				
				partsButton.setEnabled(false);
				changePartButton.setEnabled(false);
				editButton.setEnabled(false);
				addButton.setEnabled(false);
				if(authorized){
					addButton.setEnabled(true);
					deleteButton.setEnabled(true);
				}
				
				}	
			});


		
		/*Create model list and Set up model list's property*/
		modelListModel = new DefaultListModel<String>();
		modelListModel.addElement("");
		modelList = new JList<String>(modelListModel);
		modelList.setVisibleRowCount(5);
		modelList.setBorder(BorderFactory.createTitledBorder("Model:"));
		modelList.addListSelectionListener(new ListSelectionListener(){

				@Override
				public void valueChanged(ListSelectionEvent e) {
					
					//getValueIsAdjusting becomes false
					if(!e.getValueIsAdjusting() && ((JList<String>)e.getSource()).getModel().getSize() != 0){
						
						JList<String> list = (JList<String>)e.getSource();
						model = (String) list.getSelectedValue();
						editInfo[1] = model;
						yearListModel.clear();
						descListModel.clear();
						String[] years = Result.getYear(maker, model);
						for( String year : years)
							yearListModel.addElement(year);
						
						partsButton.setEnabled(false);
						changePartButton.setEnabled(false);
						editButton.setEnabled(false);
						addButton.setEnabled(false);
						if(authorized){
							addButton.setEnabled(true);
							deleteButton.setEnabled(true);
						}
					}
				}
			});
		
		
		/*Create year list and Set up year list's property*/
		rLinkList = new ArrayList<Integer>();
		yearListModel = new DefaultListModel<String>();
		yearListModel.addElement("");
		yearList = new JList<String>(yearListModel);
		yearList.setVisibleRowCount(5);
		yearList.setBorder(BorderFactory.createTitledBorder("Year:"));
		yearList.addListSelectionListener(new ListSelectionListener(){

				@Override
				public void valueChanged(ListSelectionEvent e) {
					
					//getValueIsAdjusting becomes false
					if(!e.getValueIsAdjusting() && ((JList<String>)e.getSource()).getModel().getSize() != 0){
						
						/*remove previous text in TextArea*/
						//desLength = allDes.length();
						//description.replaceRange("", 0, desLength);
						
						/*Append text to textArea */
						JList<String> list = (JList<String>)e.getSource();
						year = list.getSelectedValue();
						editInfo[2] = year;
						try {
							
							String[] autoSpec = Result.getAllDesc(maker, model, year);
							
							descListModel.clear();
							rLinkList.clear();
														
							for(String spec : autoSpec) {
								
								descListModel.addElement(spec);
								String[] tokens = spec.split(" ");
								rLinkList.add( Integer.parseInt( tokens[tokens.length - 1] ) );
							}
							
						} catch (SQLException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
						
						partsButton.setEnabled(false);
						changePartButton.setEnabled(false);
						editButton.setEnabled(false);
						if(authorized){
							addButton.setEnabled(true);
							deleteButton.setEnabled(true);
						}

						
					}
				}
			});
		
	
		/*Create description list and Set up year list's property*/
		descListModel = new DefaultListModel<String>();
		descListModel.addElement("");
		descList = new JList<String>(descListModel);
		descList.setBorder(BorderFactory.createTitledBorder("Auto Description:"));
		descList.addListSelectionListener(new ListSelectionListener() {

			@Override
			public void valueChanged(ListSelectionEvent e) {
				
				
				if(!e.getValueIsAdjusting() && ((JList<String>)e.getSource()).getModel().getSize() != 0) {
				
					JList<String> list = (JList<String>)e.getSource();
					//for debugging
					System.out.println(list.getSelectedValue());
					if (list.getSelectedValue() != null) {
						String[] tmp =  list.getSelectedValue().split(" ");
						for (int i = 3; i < editInfo.length; i++) {
							editInfo[i] = tmp[i - 3];
						}
						rLinkIndex = list.getSelectedIndex();
						
						if(authorized){
							partsButton.setEnabled(true);
							changePartButton.setEnabled(true);
							editButton.setEnabled(true);
							addButton.setEnabled(true);
							deleteButton.setEnabled(true);
						}else {
							partsButton.setEnabled(true);
							changePartButton.setEnabled(false);
							editButton.setEnabled(false);
							addButton.setEnabled(false);
							deleteButton.setEnabled(false);
						}
					}
				}
			}
			
		});
		
		
		/* create scroll for each panel */
		JScrollPane makerScroll = new JScrollPane(makerList);
		JScrollPane modelScroll = new JScrollPane(modelList);
		JScrollPane yearScroll = new JScrollPane(yearList);
		JScrollPane descScroll = new JScrollPane(descList);
		
		makerScroll.setPreferredSize(new Dimension(200,300));
		modelScroll.setPreferredSize(new Dimension(200,300));
		yearScroll.setPreferredSize(new Dimension(200,300));
		descScroll.setPreferredSize(new Dimension(500,200));
		
		//buttons
		partsButton = new JButton(" See Parts ");
		changePartButton = new JButton(" Change Part ");
		editButton = new JButton(" Edit ");
		backButton = new JButton(" Back ");
		addButton = new JButton("Add");
		deleteButton = new JButton("Delete");
		
		//disable button
		partsButton.setEnabled(false);
		changePartButton.setEnabled(false);
		editButton.setEnabled(false);
		deleteButton.setEnabled(false);
		if(authorized)
			addButton.setEnabled(true);
			
		//hide button
		if(!authorized) {
			addButton.setVisible(false);
			changePartButton.setVisible(false);
			editButton.setVisible(false);
			deleteButton.setVisible(false);
		}
		
		
		//button actionListeners
		partsButton.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e) {
				
				if (rLinkIndex >= 0) {
					Integer rLink = rLinkList.get(rLinkIndex);
					PartFrame partFrame = new PartFrame(frame, rLink);
					frame.dispose();
				}
			}
		});
		
		changePartButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				
				if(rLinkIndex >= 0) {
					Integer rLink = rLinkList.get(rLinkIndex);
					PartFrame partFrame = new PartFrame(frame, rLink, null);
					frame.dispose();
				}
			}
			
		});
		
		editButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				AutoEditFrame editFrame = new AutoEditFrame(editInfo, authorized);
				frame.dispose();
			}
		});
		
		backButton.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent e) {
				
				initialFrame.setVisible(true);
				frame.dispose();
			}
			
		});
		
		addButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				AddNewAutoFrame addAuto = new AddNewAutoFrame(frame, authorized);
				frame.dispose();
			}
		});
		
		deleteButton.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent e) {
				
				System.out.println("!!!Maker: " + editInfo[0]);
				String table = AutoMaker.makerTable.get(editInfo[0]);
//				editInfo[0] = table;
				String deleteQuery = "";
				String deleteRelation = "";
				if(editInfo[1] == null){
					
					deleteQuery = "DROP TABLE " + table;
					deleteRelation = "DELETE FROM AUTO WHERE Shortmaker = '" + table + "'";
					if(Result.deleteAuto(deleteQuery) && Result.deleteAuto(deleteRelation)){
						System.out.println("Delete Success!!!");
						AutoMaker.createMakerTable();
					}
				}else{
					deleteQuery = "DELETE FROM " + table+ " WHERE Model = '" + editInfo[1];
					
					for(int i=2; i<editInfo.length; i++){
						if(i==2 && editInfo[2] !=null)
							deleteQuery += "' AND Year = '" + editInfo[2];
						else if(i==3  && editInfo[3] !=null)
							deleteQuery += "' AND Description = '" + editInfo[3];
						else if(i==4  && editInfo[4] !=null)
							deleteQuery += "' AND LITRES = '" + editInfo[4];
						else if(i==5 && editInfo[5] !=null)
							deleteQuery += "' AND ENGINE_TYPE = '" + editInfo[5];
						else if (i==6 && editInfo[6] !=null)
							deleteQuery += "' AND CUBIC_INCHES = '" + editInfo[6];	
						else
							deleteQuery += "";
					}
					deleteQuery += "'";	
					
					System.out.println("Delete Query:" + deleteQuery);
					
					if(Result.deleteAuto(deleteQuery));
						System.out.println("Delete Success!!!");
				}
				AutoMakerFrame newMakerFrame = new AutoMakerFrame(initialFrame, authorized);
				frame.dispose();
			}
			
		});

	    autoDes.setLayout(new BorderLayout());
		autoDes.add(descScroll, BorderLayout.NORTH);
		
		buttonPanel.add(addButton);
		buttonPanel.add(deleteButton);
		buttonPanel.add(changePartButton);
		buttonPanel.add(editButton);
		buttonPanel.add(partsButton);
		buttonPanel.add(backButton);
		buttonPanel.setBorder(BorderFactory.createEmptyBorder(0, 50, 0, 50));
		autoDes.add(buttonPanel, BorderLayout.SOUTH);
		
		
		JPanel autoSelection = new JPanel();
		
		autoSelection.add(makerScroll, BorderLayout.WEST);
		autoSelection.add(modelScroll, BorderLayout.CENTER);
		autoSelection.add(yearScroll, BorderLayout.EAST);
		autoSelection.setSize(800, 250);
		autoSelection.setBorder(BorderFactory.createEmptyBorder(0, 50, 0, 50));
		autoDes.setSize(400, 250);
		autoDes.setBorder(BorderFactory.createEmptyBorder(10, 50, 10, 50));
		
		this.setLayout(new BorderLayout());
		this.add(autoSelection,BorderLayout.NORTH);
		this.add(autoDes, BorderLayout.SOUTH);
		
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
}
